package com.yh.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.yh.dao.OrderDao;
import com.yh.entity.Orderinfo;
import com.yh.service.OrderService;
import com.yh.service.PayService;
import com.yh.utils.Constants;
import com.yh.vo.OrderVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.log4j.Logger;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.Date;

/**
 * @author yuhuan
 * @date 2022/01/13
 */
@DubboService
public class PayServiceImpl implements PayService {
    /**
     * 日志
     */
    private static final Logger logger = Logger.getLogger(PayServiceImpl.class);

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private Jackson2JsonMessageConverter jackson2JsonMessageConverter;
    @DubboReference(check = false)
    private OrderService orderService;

    @Override
    public int virtualPaymentOfCode(String orderId) {
        Orderinfo order = orderDao.findOrderByOrderId(orderId);
        // 处理超时支付
        if (ObjectUtil.isEmpty(order)) {
            logger.debug(">>>>> 未查询到订单信息，订单可能超时未处理");
            return Constants.ResponseDataState.PAY_FAIL_OF_EXPIRE;
        }
        // 处理重复支付（处理超过幂等性的限制时间后，可能引发的重复支付问题）
        if (order.getOrderState() != 1) {
            logger.debug(">>>>> 订单已经处于支付状态，存在重复支付的嫌疑");
            return Constants.ResponseDataState.PAY_FAIL_OF_REPEAT;
        }
        // 取出订单应该被支付的总金额
        double orderPrice = order.getOrderPrice();
        logger.info("支付金额=>￥" + orderPrice);
        // 修改订单状态
        order.setPayTime(new Date());
        order.setOrderState(Constants.OrderData.COMPLETE_PAY);
        orderDao.updateOrderStateById(order);
        return Constants.ResponseDataState.PAY_SUCCESS;
    }

    @Override
    public int ordinaryPayment(String orderId) {
        return Constants.ResponseDataState.PAY_SUCCESS;
    }

    @Override
    public int virtualRefund(String orderId, String dateTimeStr) {
        Orderinfo order = orderDao.findOrderByOrderId(orderId);
        if (ObjectUtils.isEmpty(order)) {
            logger.debug(">>>>> 订单是无效的");
            return Constants.ResponseDataState.NULL_RESULT;
        }
        order.setOrderState(Constants.OrderData.REFUNDING);
        orderDao.updateOrderStateById(order);
        // 设置发送消息的消息转换器
        rabbitTemplate.setMessageConverter(jackson2JsonMessageConverter);
        // 将订单信息发送到消息队列
        rabbitTemplate.convertAndSend(
                Constants.RabbitMqData.PAY_EXCHANGE_NAME,
                Constants.RabbitMqData.PAY_BINDING_KEY,
                simplifyAndEncapsulation(order, dateTimeStr));
        return Constants.ResponseDataState.RESP_SUCCESS;
    }

    @Override
    public void receiveRefund(OrderVO orderVO) {
        // 获取影片的开播时间
        DateTime dateTime = DateUtil.parse(orderVO.getDateTimeStr());
        // 当前时间
        Date nowDate = new Date();
        // 获取订单信息
        Orderinfo orderinfo = orderVO.getOrderinfo();
        // 判断是否满足退款条件（开播时间必须在当前时间之后）
        if (dateTime.isAfter(nowDate)) {
            // 计算时间差
            long between = dateTime.between(nowDate, DateUnit.MINUTE);
            if (between < Constants.OrderData.FREEZE_TIME) {
                orderinfo.setOrderState(Constants.OrderData.UNABLE_REFUN);
                orderDao.updateOrderStateById(orderinfo);
                logger.info("退款失败！距离开播时间小于" + Constants.OrderData.FREEZE_TIME + "分钟");
                return;
            }
            orderinfo.setOrderState(Constants.OrderData.COMPLETE_REFUN);
            orderDao.updateOrderStateById(orderinfo);
            // 释放被占用的座位
            ((OrderServiceImpl) orderService).releaseSeat(orderinfo);
            return;
        }
        orderinfo.setOrderState(Constants.OrderData.UNABLE_REFUN);
        orderDao.updateOrderStateById(orderinfo);
        logger.info("退款失败！影片已经开始放映或已经结束放映");
    }

    /**
     * 精简订单的关键信息并封装到详情类；只抽取退款时会用到的部分关键信息，以便减少对内存的占用
     *
     * @order 订单信息
     * @dateTimeStr 影片的放映计划（日程）
     */
    private OrderVO simplifyAndEncapsulation(Orderinfo order, String dateTimeStr) {
        OrderVO orderVO = new OrderVO();
        Orderinfo orderinfo = new Orderinfo();
        // 订单ID
        orderinfo.setOrderId(order.getOrderId());
        // 订单金额
        orderinfo.setOrderPrice(order.getOrderPrice());
        // 设置场次ID，以便退票成功时进行座位的释放
        orderinfo.setScheduleId(order.getScheduleId());
        // 当前订单购买的座位信息
        orderinfo.setOrderPosition(order.getOrderPosition());
        orderVO.setOrderinfo(orderinfo);
        // 放映计划
        orderVO.setDateTimeStr(dateTimeStr);
        return orderVO;
    }
}
